package com.lds.config.center.server.common.exception;

import com.lds.config.center.server.common.enums.ServerErrorEnum;
import com.lds.management.center.common.exception.BusinessException;
import com.lds.management.center.common.model.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value =Throwable.class)
    public ResultDTO<?> throwableHandler(Throwable e) {
        log.error("throwableHandler", e);
        return ResultDTO.fail(ServerErrorEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResultDTO<?> businessExceptionHandler(BusinessException e) {
        return ResultDTO.fail(e.getExceptionMessage().getCode(), e.getMessage());
    }

    /**
     * 支持controller层校验
     */
    @ExceptionHandler(value = BindException.class)
    public ResultDTO<?> validationExceptionHandler(BindException e) {
        return ResultDTO.fail(ServerErrorEnum.INVALID_PARAM.getErrCode(), e.getFieldError().getDefaultMessage());
    }

    /**
     * 支持controller层校验
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultDTO<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        return ResultDTO.fail(ServerErrorEnum.INVALID_PARAM.getErrCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 支持service层校验
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultDTO<?> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            return ResultDTO.fail(ServerErrorEnum.INVALID_PARAM.getErrCode(), constraintViolation.getMessage());
        }
        return ResultDTO.fail(ServerErrorEnum.INVALID_PARAM);
    }

}
